﻿using System;
using System.Data;
using System.Web.UI;
using DevExpress.Web.ASPxHeadline;
using DevExpress.Web.ASPxClasses;
using DevExpress.Web.ASPxCallback;

using LMD.Constant;
using LMD.Lib.Controls;
using LMD.Lib.DataClass;
using LMD.Lib.Interface;
using LMD.Lib.Oracle;

public partial class NewsFeed : ICPGeneralPage
{
    #region Properties
    public int m_idNewest
    {
        get
        {
            int i = 0;
            try { i = int.Parse(idNewest.InnerHtml); }
            catch { /* LET IT BE ZERO */ }
            return i;
        }
        set { idNewest.InnerHtml = value.ToString(); }
    }
    public int m_idOldest
    {
        get
        {
            int i = 0;
            try { i = int.Parse(idOldest.InnerHtml); }
            catch { /* LET IT BE ZERO */ }
            return i;
        }
        set { idOldest.InnerHtml = value.ToString(); }
    }
    public int m_iPageMode
    {
        get
        {
            if (!String.IsNullOrEmpty(Request.QueryString["mode"]))
            {
                switch (Request.QueryString["mode"].ToUpper())
                {
                    case "PROFILE": return 1;
                    case "CUSTOMER": return 2;
                    default: return 0;
                }
            }
            else
            {
                return 0;
            }
        }
    }

    public int m_iPageNumber
    {
        get
        {
            if (!String.IsNullOrEmpty(Request.QueryString["page"]))
            {
                try
                {
                    return int.Parse(Request.QueryString["page"]);
                }
                catch
                {
                    return 1;
                }
            }
            else
            {
                return 1;
            }
        }
    }
    public String m_sxViewUserName
    {
        get
        {
            if (!String.IsNullOrEmpty(Request.QueryString["uid"]))
            {
                Cached.ICPUserTable ccUser = new Cached.ICPUserTable();
                return ccUser.GetUserData(Request.QueryString["uid"]).sxName;
            }
            else
            {
                return m_sxUserName;
            }
        }
    }
    public String m_sxViewUserId
    {
        get
        {
            if (!String.IsNullOrEmpty(Request.QueryString["uid"]))
            {
                return Request.QueryString["uid"];
            }
            else
            {
                return m_sxUID;
            }
        }
    }
    public int m_iNewsFeedId
    {
        get
        {
            if (!String.IsNullOrEmpty(Request.QueryString["nfid"]))
            {
                return int.Parse(Request.QueryString["nfid"]);
            }
            else
            {
                return 0;
            }
        }
    }

    #endregion Properties

    #region Event Handlers

    protected override void Page_Load(object sender, EventArgs e)
    {
        base.Page_Load(sender, e);

        Page.Title = "ICP Lintasarta: News Feed";
        if(!IsPostBack && !IsCallback)
        {
            if(m_iNewsFeedId > 0)
            {
                pnlNewsFeed.InnerHtml = OpenSingleFeed(m_iNewsFeedId);
                tmrNewsFeed.Enabled = false;
                return;
            }

            if (m_iPageMode == 1) // PROFILE
            {
                tmrNewsFeed.Enabled = false;
                return;
            }
            else if (m_iPageMode == 2) // CUST LIST
            {
                pnlNewsFeed.InnerHtml = InitCompanyList(m_sxViewUserId);
                tmrNewsFeed.Enabled = false;
                return;
            }

            pnlNewsFeed.InnerHtml = InitNewsFeed();
            tmrNewsFeed.Interval = KGlobal.NEWS_FEED_REFRESH_INTERVAL;
        }
    }

    protected void cbkMain_Callback(object sender, CallbackEventArgs e)
    {
        System.Threading.Thread.Sleep(KGlobal.AJAX_WAIT_TIME);
        int id = int.Parse(e.Parameter);
        e.Result = ShowComment(id);
    }

    protected void cbkUpdate_Callback(object sender, CallbackEventArgs e)
    {
        System.Threading.Thread.Sleep(KGlobal.AJAX_WAIT_TIME);

        e.Result = HandleUpdate(e.Parameter);
    }

    protected void cbkOlder_Callback(object sender, CallbackEventArgs e)
    {
        System.Threading.Thread.Sleep(KGlobal.AJAX_WAIT_TIME);
        int id = int.Parse(e.Parameter);
        e.Result = GetOlderFeed(id);
    }

    protected void cbkComment_Callback(object sender, CallbackEventArgs e)
    {
        System.Threading.Thread.Sleep(KGlobal.AJAX_WAIT_TIME);
        e.Result = DoComment(e.Parameter);
    }


    

    
    #endregion Event Handlers

    #region Custom Methods
    private String OpenSingleFeed(int iNewsFeedId)
    {
        Cached.NewsFeedTable ccNF = new Cached.NewsFeedTable();
        NewsFeedData arrNF = ccNF.GetNewsFeed(iNewsFeedId);

        return arrNF == null ?
            String.Format("News Feed with ID {0} is not exist!", iNewsFeedId.ToString()) :
            arrNF.BuildNewsFeedItem();
    }

    private String InitNewsFeed()
    {
        Cached.NewsFeedTable ccNF = new Cached.NewsFeedTable();
        NewsFeedData[] arrNF = m_sxViewUserId == m_sxUID ? 
            ccNF.GetNewsFeedList() :
            ccNF.GetUserNewsFeedList(m_sxViewUserId);

        if (arrNF.Length > 0)
        {
            m_idNewest = arrNF[0].ID;
            m_idOldest = arrNF[arrNF.Length - 1].ID;
        }
        else
        {
            m_idNewest = m_idOldest = 0;
        }

        return arrNF.BuildNewsFeedList();
    }

    private String HandleUpdate(String sxParam)
    {
        int iNewestId = -1;

        String[] sxSplitted = sxParam.Split(new String[] { KGlobal.DELIMITER }, StringSplitOptions.None);

        if (sxSplitted.Length > 1)
        {
            if (sxSplitted[0].ToUpper() == "DELETE")
            {
                int iDeletedId = int.Parse(sxSplitted[1]);

                DBQuery.NewsFeedTable.DeleteNewsFeed(iDeletedId);
                return String.Empty;
            }
            else if (sxSplitted[0].ToUpper() == "UPDATE_STATUS")
            {
                iNewestId = int.Parse(sxSplitted[2]);

                NewsFeedData nf = new NewsFeedData();
                nf.sxContent = sxSplitted[1];
                nf.sxUserName_Poster = m_sxUserName;
                nf.sxUserId_Poster = m_sxUID;
                nf.sxSourceName = "ICP";
                nf.iSourceId = 1;

                if (m_sxViewUserId != m_sxUID)
                {
                    nf.sxUserName_Target = m_sxViewUserName;
                    nf.sxUserId_Target = m_sxViewUserId;

                    DBLib dbl = new DBLib();
                    dbl.BeginTransaction();

                    try
                    {
                        DBQuery.NewsFeedTable.SaveNewsFeed(dbl, nf);
                        DBQuery.NotificationTable.InsertNotification_WallPost(dbl, nf.ID);
                        dbl.EndTransaction(true);
                    }
                    catch (Exception ex)
                    {
                        dbl.EndTransaction(false);
                        throw ex;
                    }
                }
                else
                {
                    DBQuery.NewsFeedTable.SaveNewsFeed(nf);
                }
            }
        }
        else
        {
            iNewestId = int.Parse(sxParam);
        }

        return UpdateFeed(iNewestId);
    }

    private String UpdateFeed(int iNewest)
    {
        Cached.NewsFeedTable ccNF = new Cached.NewsFeedTable();
        NewsFeedData[] arrNF = m_sxViewUserId == m_sxUID ?
            ccNF.GetNewsFeedUpdateList(iNewest) :
            ccNF.GetUserNewsFeedUpdateList(m_sxViewUserId, iNewest);

        String sxOutput = String.Empty;

        sxOutput += arrNF.BuildNewsFeedList();

        m_idNewest = arrNF.Length > 0 ? arrNF[0].ID : iNewest;

        sxOutput = m_idNewest.ToString() + KGlobal.DELIMITER + sxOutput;
        return sxOutput;
    }

    private String DoComment(String sxParameter)
    {
        String[] sxParams = sxParameter.Split(new String[] { KGlobal.DELIMITER }, StringSplitOptions.None);

        CommentData cmData = new CommentData();
        cmData.NewsFeedID = int.Parse(sxParams[0]);
        cmData.sxContent = sxParams[1];
        cmData.sxUserName = m_sxUserName;
        cmData.sxUserId = m_sxUID;

        DBQuery.NewsFeedTable.SaveNewsFeedComment(cmData);

        Cached.NewsFeedTable ccNF = new Cached.NewsFeedTable();
        int iComment = ccNF.GetCommentCount(cmData.NewsFeedID);

        return iComment + KGlobal.DELIMITER + cmData.BuildCommentItem();
    }

    private String GetOlderFeed(int iOldest)
    {
        bool IsSearchMode = (Master as IMasterPage).IsSearchMode();

        Cached.NewsFeedTable ccNF = new Cached.NewsFeedTable();
        NewsFeedData[] arrNF = null;

        if (IsSearchMode)
        {
            String sxFilter = (Master as IMasterPage).ReadSearchQuery();

            arrNF = m_sxViewUserId == m_sxUID ?
             ccNF.GetOlderFeedFilteredList(iOldest, sxFilter) :
             ccNF.GetUserOlderFeedFilteredList(m_sxViewUserId, iOldest, sxFilter);
        }
        else
        {
            arrNF = m_sxViewUserId == m_sxUID ?
             ccNF.GetNewsFeedOlderList(iOldest) :
             ccNF.GetUserNewsFeedOlderList(m_sxViewUserId, iOldest);
        }

        String sxOutput = String.Empty;

        sxOutput += arrNF.BuildNewsFeedList();

        m_idOldest = arrNF.Length > 0 ? arrNF[arrNF.Length-1].ID : iOldest;

        sxOutput = m_idOldest.ToString() + KGlobal.DELIMITER + sxOutput;
        return sxOutput;
    }

    private String ShowComment(int iNewsFeedId)
    {
        Cached.NewsFeedTable ccNF = new Cached.NewsFeedTable();
        CommentData[] arrCD = ccNF.GetCommentList(iNewsFeedId);
        
        String sxOutput = String.Empty;

        for (int i = 0; i < arrCD.Length; i++)
        {
            sxOutput += arrCD[i].BuildCommentItem();
        }

        sxOutput += KGlobal.DELIMITER + NewsFeedManager.BuildCommentForm(iNewsFeedId, m_sxUID);
        return sxOutput;
    }

    public String GetClass(int iElementName)
    {
        return (iElementName == m_iPageMode) ? "_selected" : "";
    }

    public String InitUserData()
    {
        Cached.ICPUserTable ccUser = new Cached.ICPUserTable();
        UserData ud = ccUser.GetUserData(m_sxViewUserId);

        return ud.BuildFieldset_UserProfile();
    }


    private String InitCompanyList(String sxUserId)
    {
        return NewsFeedManager.BuildCustomerList(sxUserId, m_iPageNumber);
    }

    private string SearchCompanyList(String sxUserId, String sxSearchQuery)
    {
        return NewsFeedManager.BuildCustomerList_BySearch(sxUserId, sxSearchQuery);        
    }
    protected override void DoSearch(String sxSearchQuery)
    {
        tmrNewsFeed.Enabled = false;

        if (m_iPageMode == 2) // CUST LIST
        {
            pnlNewsFeed.InnerHtml = SearchCompanyList(m_sxViewUserId, sxSearchQuery);
            return;
        }

        Cached.NewsFeedTable ccNF = new Cached.NewsFeedTable();
        NewsFeedData[] arrNF = m_sxViewUserId == m_sxUID ?
            ccNF.GetNewsFeedFilteredList(sxSearchQuery) :
            ccNF.GetUserNewsFeedFilteredList(m_sxViewUserId, sxSearchQuery);

        if (arrNF.Length > 0)
        {
            m_idNewest = arrNF[0].ID;
            m_idOldest = arrNF[arrNF.Length - 1].ID;
        }
        else
        {
            m_idNewest = 0;
            m_idOldest = 0;
        }

        pnlNewsFeed.InnerHtml = arrNF.BuildNewsFeedList();

    }

   
    #endregion Custom Methods
}